package com.mydesignpattern.beijing.proxy.dynamic;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


/**
 * 利用cglib提供的方法实现的动态代理handler
 * Created by Administrator on 2017/5/16 0016.
 */
public class CGLibProxyHandler implements MethodInterceptor {

    private Object target;

    //创建代理对象
    public Object getInstance(Object target){
        this.target = target;
        Enhancer enhancer = new Enhancer();
        //设置需要创建子类的类
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }


    //实现MethodInterceptor接口方法
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object object ;
        System.out.println("方法执行前日志");
        object = methodProxy.invokeSuper(o, args);
        System.out.println("方法执行后日志");
        return object;
    }
}
